/*
 * Project: Hell Watch
 * Author: pajoke
 * Copyright: (C) 2014 Hell Prototypes
 * License: GNU GPL v3 (see License.txt)
 * Web: http://www.hellprototypes.com
 */


#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <util/atomic.h>
#include "millis/millis.h"
#include "common.h"


static volatile millis_t milliseconds;

// Initialise library
void millis_init()
{
	TCC1.PER = 1999;
	TCC1.INTCTRLA = 0x03; //HI Pri
	MILLIS_TIMER_EN();//DIV 8,  2M

	sei();
}

// Get current milliseconds
millis_t millis_get()
{
	millis_t ms;

	ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
	{
		ms = milliseconds;
	}

	return ms;
}

ISR(TCC1_OVF_vect)
{
	milliseconds++;
}

void ms_delay(millis_t ms)
{
	millis_t current, base, delay;

	base = millis_get();

	delay = ms;

	do {
		current = millis_get();

		if(current >= base) {
			if( current - base >= delay) {
				return;
			}
		} else {
			delay = delay - (0xFFFF - base);
			base = 0;
		}
        sleep_mode();
	} while(1);
}


